
//这个函数在整个wps加载项中是第一个执行的
import {
  getOriginURL,
  GetDocParamsValue,
  setDocParamsValue, setPluginStorageItem, getPluginStorageItem,
} from "../common/common";
import {constWpsEnum, EnumDocSaveFlag, WPS_Enum} from "@/components/WpsOffice/wps/enum";
import {
  pInitParameters,
  AddDocumentEvent,
  saveToServer,
  pGet996CodeDocLabel,
  pSetUserNameLabelControl,
  OnBtnClearRevDoc,
  OnOpenRevisions,
  OnCloseRevisions,
  OnAcceptAllRevisions,
  OnRejectAllRevisions,
  OnShowDialog,
  createTaskPane,
  importLocalFile,
  DoInsertPicToDoc,
  DoInsertWaterToDoc,
  OnInsertDateClicked,
  OnPageSetupClicked,
  OnPrintDocBtnClicked,
  OnBtnSaveAsLocalFile,
  OnDoChangeToOtherDocFormat,
} from "@/components/WpsOffice/wps/onWpsControl";
import {

  pCheckIs996CodeOffice, ribbonWpsTaName,

} from "@/components/WpsOffice/wps/wpsCommon";

function OnAddinLoad(ribbonUI) {
  try {
    if (typeof window.Application.ribbonUI != 'object') {
      window.Application.ribbonUI = ribbonUI
    }

    if (typeof window.Application.Enum != 'object') {
      // 如果没有内置枚举值
      window.Application.Enum = WPS_Enum
    }

    //配置控制的初始化过程
    pInitParameters();
    //挂接文档事件处理函数
    AddDocumentEvent();
  }catch (e) {
    alert("OnAddinLoad执行失败："+e.message)
    alert(e.stack)
  }

  return true
}

var WebNotifycount = 0
function OnAction(control) {
  try {
    let eleId;
    let tag;
    if (typeof control == "object" && arguments.length == 1) { //针对Ribbon的按钮的
      control = control;
    } else if (typeof control == "undefined" && arguments.length > 1) { //针对idMso的
      control = arguments[1];
    } else if (typeof control == "boolean" && arguments.length > 1) { //针对checkbox的
      control = arguments[1];
    } else if (typeof control == "number" && arguments.length > 1) { //针对combox的
      control = arguments[2];
    }

    eleId = control.Id;
    tag = control.Tag;

    const doc = window.Application.ActiveDocument

    // let amisKey = null;
    // if(eleId.indexOf("amisShowDialog-") !== -1 ){
    //   amisKey = eleId.replace("amisShowDialog-","")
    //   eleId = "amisShowDialog-" ;
    // }
    // if(eleId.indexOf("amisShowTaskPane-") !== -1 ){
    //   amisKey = eleId.replace("amisShowTaskPane-","")
    //   eleId = "amisShowTaskPane-" ;
    // }

    switch (eleId) {
      // *****************************  加载项
      case 'btnShowDialog': {
        OnShowDialog("/wps-office/wps/index.html", "996全干系统", 500, 300)
        break
      }
      case 'btnShowTaskPane': {
        createTaskPane("/wps-office/wps/index.html")
      }
        break
      case 'amisShowDialog': {
        OnShowDialog("/wps-office/wps/index.html#/SinglePage/amisForm/AmisFormShowByKey?amisFormShowFormKey="+tag, "996全干系统", 500, 300)
        break
      }
      case 'amisShowTaskPane': {
        createTaskPane("/wps-office/wps/index.html#/SinglePage/amisForm/AmisFormShowByKey?amisFormShowFormKey="+tag)
      }
        break
      case 'btnWebNotify': {
        let currentTime = new Date()
        let timeStr =
          currentTime.getHours() + ':' + currentTime.getMinutes() + ':' + currentTime.getSeconds()
        let pluginStorageItem = getPluginStorageItem(doc.FullName);
        let l_objParams = JSON.parse(pluginStorageItem);
        l_objParams["WebNotifycount"] = WebNotifycount ;
        window.Application.OAAssist.WebNotify(JSON.stringify(l_objParams),
          // '这行内容由wps加载项主动送达给业务系统，文档参数：'+pluginStorageItem+'，比如时间值:' +
          // timeStr +
          // '，次数：' +
          // ++WebNotifycount,
          true
        )
      }
        break
      case 'saveToServer': {
        saveToServer()
      }
        break
      case "btnSaveAsFile": //另存为本地文件
        OnBtnSaveAsLocalFile();
        break;
      case "btnChangeToPDF": //转PDF文档并上传
        OnDoChangeToOtherDocFormat(".pdf");
        break;
      case 'importLocalFileInsert': {
        importLocalFile("Insert")
      }
        break
      case 'importLocalFileAppend': {
        importLocalFile("Append")
      }
        break
      case 'importLocalFileReplace': {
        importLocalFile("Replace")
      }
        break
      case "btnClearRevDoc": //执行 清稿 按钮
        OnBtnClearRevDoc();
        break;
      case "btnOpenRevision": //打开修订
      {
        setDocParamsValue(doc,constWpsEnum.RevisionEnableFlag,true);
        // let bFlag = wps.PluginStorage.getItem(constStrEnum.RevisionEnableFlag)
        // wps.PluginStorage.setItem(constStrEnum.RevisionEnableFlag, !bFlag)
        //通知wps刷新以下几个按钮的状态
        wps.ribbonUI.InvalidateControl("btnOpenRevision")
        wps.ribbonUI.InvalidateControl("btnCloseRevision")
        OnOpenRevisions(); //
        break;
      }
      case "btnCloseRevision": //关闭修订
      {
        setDocParamsValue(doc,constWpsEnum.RevisionEnableFlag,false);
        // let bFlag = wps.PluginStorage.getItem(constStrEnum.RevisionEnableFlag)
        // wps.PluginStorage.setItem(constStrEnum.RevisionEnableFlag, !bFlag)
        //通知wps刷新以下几个按钮的状态
        wps.ribbonUI.InvalidateControl("btnOpenRevision")
        wps.ribbonUI.InvalidateControl("btnCloseRevision")
        OnCloseRevisions();
        break;
      }
      case "btnAcceptAllRevisions": //接受所有修订功能
        OnAcceptAllRevisions();
        break;
      case "btnRejectAllRevisions": //拒绝修订
        OnRejectAllRevisions();
        break;
      //------------------------------------
      //插入书签
      case "btnInsertBookmark":
        createTaskPane("/wps-office/wps/index.html#/SinglePage/office/insertBookmark")
        break;
      //导入模板
      case "btnImportTemplate":
        OnShowDialog("/wps-office/wps/index.html#/SinglePage/office/importTemplate", "导入模板", 500, 300)
        break;
      case "btnInsertPic": //插入图片
        DoInsertPicToDoc();
        break;
      case "btnInsertWater":
        DoInsertWaterToDoc()
        break;
      case "btnInsertDate": //插入日期
        OnInsertDateClicked();
        break;
      case "btnPageSetup": //打开页面设置
        OnPageSetupClicked();
        break;
      case "btnPrintDOC": // 打开打印设置
        OnPrintDocBtnClicked();
        break;

      // *****************************  命令
      case "FileSave": //通过idMso进行「保存」功能的自定义
      {
        if (pCheckIs996CodeOffice()) { //文档来源是业务系统的，做自定义
          alert("这是996全干系统文档，将Ctrl+S动作做了重定义，可以调用OA的保存文件流到业务系统的接口。")
          saveToServer();
        } else { //本地的文档，期望不做自定义，通过转调idMso的方法实现
          // wps.WpsApplication().CommandBars.ExecuteMso("FileSave");
          wps.WpsApplication().CommandBars.ExecuteMso("SaveAll");
          //此处一定不能去调用与重写idMso相同的ID，否则就是个无线递归了，即在这个场景下不可调用FileSaveAs和FileSaveAsMenu这两个方法
        }
        break;
      }

      case "SaveAll": //保存所有文档
        break
      case "Copy": //复制
        break
      case "Cut": //剪切
        break
      case "FileSaveAsMenu": //另存为
      {
        if (pCheckIs996CodeOffice()) { //文档来源是业务系统的，做自定义
          alert("这是996全干系统文档，将Ctrl+S动作做了重定义，可以调用OA的保存文件流到业务系统的接口。")
          saveToServer();
        } else { //本地的文档，期望不做自定义，通过转调idMso的方法实现
          // wps.WpsApplication().CommandBars.ExecuteMso("FileSave");
          wps.WpsApplication().CommandBars.ExecuteMso("SaveAll");
          //此处一定不能去调用与重写idMso相同的ID，否则就是个无线递归了，即在这个场景下不可调用FileSaveAs和FileSaveAsMenu这两个方法
        }
        break;
      }
      case "FileSaveAsPicture": //另存为
        break
      case "SaveAsPicture": //另存为
        break
      case "FileMenuSendMail": //另存为
        break
      case "FileSaveAs": //另存为
      {
        if (pCheckIs996CodeOffice()) { //文档来源是业务系统的，做自定义
          alert("这是996全干系统文档，将Ctrl+S动作做了重定义，可以调用OA的保存文件流到业务系统的接口。")
          saveToServer();
        } else { //本地的文档，期望不做自定义，通过转调idMso的方法实现
          // wps.WpsApplication().CommandBars.ExecuteMso("FileSave");
          wps.WpsApplication().CommandBars.ExecuteMso("SaveAll");
          //此处一定不能去调用与重写idMso相同的ID，否则就是个无线递归了，即在这个场景下不可调用FileSaveAs和FileSaveAsMenu这两个方法
        }
        break;
      }
      case "SaveAsPDF": //PDF
        break
      case "FileSaveAsPDF": //PDF
        break
      case "ExportToPDF": //PDF
        break
      case "FileSaveAsPdfOrXps": //PDF
        break
      case "SaveAsOfd": //OFD
        break
      case "FileSaveAsOfd": //OFD
        break
      case "FilePrint": //打印
        break
      case "FilePrintMenu": //打印
        break
      case "FilePrintPreview": //打印
        break
      case "ReviewTrackChangesMenu": //文档修订
        break
      case "ReviewRejectChangeMenu": //文档修订
        break
      case "ReviewAcceptChangeMenu": //文档修订
        break
      case "FileNewMenu": //文档新建
        break
      case "FileNew": //文档新建
        break
      case "WindowNew": //文档新建
        break
      case "FileNewBlankDocument": //文档新建
        break

      // *****************************  右键
      case "ShowAlert_ContextMenuText":
      {
        let selectText = wps.WpsApplication().Selection.Text;
        alert("您选择的内容是：\n" + selectText);
        break;
      }

      default:
        break
    }
  }catch (e){
    alert(e.message)
    alert(e.stack)
  }
  return true
}

function GetImage(control) {
  let eleId;
  if (typeof control == "object" && arguments.length == 1) { //针对Ribbon的按钮的
    eleId = control.Id;
  } else if (typeof control == "undefined" && arguments.length > 1) { //针对idMso的
    eleId = arguments[1].Id;
  } else if (typeof control == "boolean" && arguments.length > 1) { //针对checkbox的
    eleId = arguments[1].Id;
  } else if (typeof control == "number" && arguments.length > 1) { //针对combox的
    eleId = arguments[2].Id;
  }
  switch (eleId) {
    case 'saveToServer':
      return '../images/w_Save.png'
    case "btnSaveAsFile": //另存为本地文件
      return "../images/w_SaveAs.png";
    case "btnChangeToPDF": //输出为PDF格式
      return "../images/w_PDF.png";
    case 'importLocalFile':
      return '../images/w_ImportLocalFile.png'
    case 'importLocalFileInsert':
      return '../images/w_ImportDoc.png'
    case 'importLocalFileAppend':
      return '../images/w_ImportDoc.png'
    case 'importLocalFileReplace':
      return '../images/w_ImportDoc.png'
    //打开 修订
    case "btnOpenRevision":
      return "../images/w_OpenRev.png";
    //关闭修订
    case "btnCloseRevision":
      return "../images/w_CloseRev.png";
    // 接受修订
    case "btnAcceptAllRevisions":
      return "../images/w_AcceptRev.png";
    // 拒绝修订
    case "btnRejectAllRevisions":
      return "../images/w_RejectRev.png";
    //清稿
    case "btnClearRevDoc":
      return "../images/w_DocClear.png"
    case "btnInsertBookmark":
      return "../images/c_bookmark.png";
    case "btnImportTemplate":
      return "../images/w_ImportDoc.png";
    //插入图片
    case "btnInsertPic":
      return "../images/w_InsPictures.png";
    //插入日期
    case "btnInsertDate":
      return "../images/w_InsDate.png";
    //打开页面设置
    case "btnPageSetup":
      return "../images/w_PageGear.png";
    //插入水印
    case "btnInsertWater":
    // 打印设置
    case "btnPrintDOC":
      return "../images/c_printDoc.png";
    default:
  }
  return '../images/c_default.png'
}

function OnGetEnabled(control) {
  const eleId = control.Id
  const doc = window.Application.ActiveDocument
  switch (eleId) {
    case "btnCloseRevision":
    {
      let bFlag = GetDocParamsValue(doc,constWpsEnum.RevisionEnableFlag);
      // let bFlag = wps.PluginStorage.getItem(constStrEnum.RevisionEnableFlag)
      return bFlag
    }
    case "btnOpenRevision":
    {
      let bFlag = GetDocParamsValue(doc,constWpsEnum.RevisionEnableFlag);
      // let bFlag = wps.PluginStorage.getItem(constStrEnum.RevisionEnableFlag)
      return !bFlag
    }
    default:
      break
  }
  return true
}

function OnGetVisible(control) {
  let eleId;
  if (typeof control == "object" && arguments.length == 1) { //针对Ribbon的按钮的
    eleId = control.Id;
  } else if (typeof control == "undefined" && arguments.length > 1) { //针对idMso的
    eleId = arguments[1].Id;
  } else if (typeof control == "boolean" && arguments.length > 1) { //针对checkbox的
    eleId = arguments[1].Id;
  } else if (typeof control == "number" && arguments.length > 1) { //针对combox的
    eleId = arguments[2].Id;
  }
  console.log(eleId)
  if(eleId == ribbonWpsTaName()){
    return pCheckIs996CodeOffice() ;
  }
  return true
}

function OnGetLabel(control) {
  const eleId = control.Id
  switch (eleId) {
    case 'lblDocSourceValue': {
      return pCheckIs996CodeOffice() ? "全干系统文件" : "非全干系统文件";
    }
    case 'lblDocLandModeValue': {
      return pGet996CodeDocLabel() ;
    }
    case 'lblUserNameValue': {
      return pSetUserNameLabelControl() ;
    }

    case "btnOpenRevision": //打开修订按钮
      return "打开修订";
    case "btnCloseRevision": //关闭修订按钮
      return "关闭修订";
    case "btnClearRevDoc": //显示 清稿
      return "清稿";
    case "btnAcceptAllRevisions": //显示 接受修订
      return "接受修订";
    case "btnRejectAllRevisions": //显示 拒绝修订
      return "拒绝修订";
    case "btnInsertBookmark":
      return "导入书签";
    case "btnImportTemplate":
      return "导入模板";
  }
  return ''
}

function OnNewDocumentApiEvent(doc) {
  alert('新建文件事件响应，取文件名: ' + doc.Name)
}




//这些函数是给wps客户端调用的
export default {
  OnAddinLoad,
  OnAction,
  GetImage,
  OnGetEnabled,
  OnGetVisible,
  OnGetLabel,
  OnNewDocumentApiEvent
}
